package shajie.shajun.mmhf.Base;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import java.text.SimpleDateFormat;

import shajie.shajun.mmhf.Interface.BacktoHome;
import shajie.shajun.mmhf.MyApplication;
import shajie.shajun.mmhf.Public_Data;

/**
 * Created by Administrator on 2017/11/3.
 */

public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity {
    private B bingding;
    private BacktoHome backtoHome;
    private MyApplication mMyApplication;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bingding= DataBindingUtil.setContentView(this,setlayoutid());
        if (mMyApplication==null){
            mMyApplication=(MyApplication) getApplication();
        }
        mMyApplication.addActivity(this);
        init(bingding);
        backtoHome=new BacktoHome(this);
    }
    public abstract int setlayoutid();
    public abstract void init(B bingding);
    public void toast(String s){
        Toast.makeText(this, s,Toast.LENGTH_SHORT).show();
    }
    public void toast(int s){
        Toast.makeText(this, String.valueOf(s),Toast.LENGTH_SHORT).show();
    }
    public void toast(float s){
        Toast.makeText(this, String.valueOf(s),Toast.LENGTH_SHORT).show();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (Public_Data.number<=0) {
                moveTaskToBack(false);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onResume() {
        unregisterComponentCallbacks(backtoHome);
        if (!Public_Data.backtohome) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//(12小时制 yyyy-MM-dd HH:mm:ss a)
            String date = sdf.format(new java.util.Date());
            try {
                Public_Data.startdate = sdf.parse(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Public_Data.backtohome = true;
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        registerComponentCallbacks(backtoHome);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMyApplication.removeActivity(this);
        unregisterComponentCallbacks(backtoHome);
    }
}
